<template>
    <div class="chat-box">
        <template class="chat-message" v-for="message in userlist">
            <el-col :span="18" :offset="4">
                <div :style="stylechange(message.chat.msg)" class="message-content">
                    <p class=msgdate>{{ message.chat.msg_date }}</p>
                    <div>{{ message.chat.msg }}</div>
                </div>
            </el-col>
        </template>
        <el-input
                placeholder="请输入内容"
                v-model="input"
                clearable class="inputl">
        </el-input>
        <el-button type="info" plain @click="MsgClick(input)">发送</el-button>
    </div>
</template>

<script>
    import axios from 'axios';

    export default {
        name: "chatting",
        data() {
            return {
                userlist: [],
                input: '',
                username: '',
            }
        },
        created() {
            // 在组件创建时启动定时执行
            this.intervalId = setInterval(this.chatMethod, 1000);
        },
        beforeDestroy() {
            // 在组件销毁前清除定时器
            clearInterval(this.intervalId);
        },
        methods: {
            MsgClick(event) {
                let msg = '@' + this.message + ':' + event
                axios.post('http://127.0.0.1:8000/api/chatmsg/', {
                    'username': this.username,
                    'msg': msg,
                }, {
                    headers: {
                        token: sessionStorage.getItem('token'),
                    },
                })
                this.input = ''
            },


            stylechange(msg) {
                let name = msg.slice(1).split(":")[0];
                if (name == this.username) {
                    return ' float: left;'
                } else {
                    return ' float: right;'
                }
            },
            chatMethod() {
                axios.get('http://127.0.0.1:8000/api/chatmessage/', {
                        headers: {
                            token: sessionStorage.getItem('token')
                        },
                        params: {
                            username: sessionStorage.getItem('username'),
                            toname: this.message
                        }
                    }
                ).then(response => {
                    this.userlist = response.data.results
                    this.username = sessionStorage.getItem('username')
                })
                    .catch(error => {
                        console.log(error);
                    });
            }
        },
        props: ['message'],

    }
</script>

<style scoped>

    .message-content {
        float: left;
        background-color: #f2f2f2;
        border-radius: 8px;
        padding: 10px;
        margin-bottom: 10px;
        width: 40%;
    }

    .msgdate {
        float: left;
        width: 100%;
    }

    .inputl {
        width: 50%;
    }
</style>


